import winreg
import tkinter as tk
from tkinter import messagebox
from tkinter import filedialog


def add_right_click_menu(menu_name, menu_command, icon_path):
    key_path = f'Directory\\Background\\shell\\{menu_name}'

    try:
        # 检查主键是否存在
        if not check_registry(menu_name):
            create_menu(menu_name, menu_command, icon_path, key_path)
            return True
        else:
            # 弹出提示询问是否覆盖
            if messagebox.askyesno("提示", f"菜单 '{menu_name}' 已存在，是否覆盖？"):
                create_menu(menu_name, menu_command, icon_path, key_path)
                return True
            else:
                return False
    except Exception as e:
        messagebox.showerror("错误", f"添加失败: {str(e)}")
        return False


# 创建新的菜单项
def create_menu(menu_name, menu_command, icon_path, key_path):
    with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, key_path) as key:
        winreg.SetValue(key, '', winreg.REG_SZ, menu_name)

        # 添加图标
        winreg.SetValueEx(key, "Icon", 0, winreg.REG_SZ, icon_path)

    # 创建命令项
    command_key_path = f'{key_path}\\command'
    with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, command_key_path) as command_key:
        winreg.SetValue(command_key, '', winreg.REG_SZ, menu_command)


def check_registry(menu_name):
    key_path = f'Directory\\Background\\shell\\{menu_name}'
    try:
        with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, key_path):
            return True
    except FileNotFoundError:
        return False

def delete_right_click_menu(menu_name):
    """删除指定名称的右键菜单"""
    key_path = f'Directory\\Background\\shell\\{menu_name}'
    try:
        # 检查菜单是否存在
        if check_registry(menu_name):
            # 删除整个菜单项及其子项
            winreg.DeleteKey(winreg.HKEY_CLASSES_ROOT, f'{key_path}\\command')
            winreg.DeleteKey(winreg.HKEY_CLASSES_ROOT, key_path)
            return True
        else:
            messagebox.showwarning("警告", f"菜单 '{menu_name}' 不存在")
            return False
    except Exception as e:
        messagebox.showerror("错误", f"删除失败: {str(e)}")
        return False


def on_button_click():
    # 菜单名称
    menu_name = entry_menu_name.get()
    # 图标路径
    icon_path = entry_command.get()
    # 菜单命令 "%V"获取当前文件路径
    menu_command = entry_command.get() + ' "%V"'

    # if menu_name and menu_command:
        # if add_right_click_menu(menu_name, menu_command, icon_path):
        #     if check_registry(menu_name):
        #         messagebox.showinfo("提示", "右键菜单添加成功")
        #     else:
        #         messagebox.showinfo("提示", "添加成功，但找不到注册表项")
    # else:
    #     messagebox.showwarning("警告", "请填写菜单名称和路径")
    if menu_name and menu_command:
        # 检查文件是否存在
        import os
        if not os.path.exists(entry_command.get()):
            messagebox.showwarning("警告", "选择的可执行文件不存在")
            return

        if add_right_click_menu(menu_name, menu_command, icon_path):
            if check_registry(menu_name):
                messagebox.showinfo("提示", "右键菜单添加成功")
            else:
                messagebox.showinfo("提示", "添加成功，但找不到注册表项")
    else:
        messagebox.showwarning("警告", "请填写菜单名称和选择可执行文件")

# 添加文件选择函数
def browse_file():
    """打开文件选择对话框"""
    file_path = filedialog.askopenfilename(
        title="选择可执行文件",
        filetypes=[
            ("可执行文件", "*.exe"),
            ("批处理文件", "*.bat"),
            ("所有文件", "*.*")
        ]
    )
    if file_path:
        entry_command.delete(0, tk.END)
        entry_command.insert(0, file_path)

def on_delete_button_click():
    """处理删除按钮点击事件"""
    # 获取菜单名称
    menu_name = entry_menu_name.get()

    if menu_name:
        # 确认删除操作
        if messagebox.askyesno("确认删除", f"确定要删除菜单 '{menu_name}' 吗？"):
            if delete_right_click_menu(menu_name):
                messagebox.showinfo("提示", "右键菜单删除成功")
                # 清空输入框
                entry_menu_name.delete(0, tk.END)
    else:
        messagebox.showwarning("警告", "请输入要删除的菜单名称")

# 创建 GUI
root = tk.Tk()
root.title("win右键菜单管理器")

# 设置窗口大小
window_width = 400
window_height = 300

# 获取屏幕宽度和高度
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

# 计算窗口左上角的位置，使其居中
x_position = (screen_width // 2) - (window_width // 2)
y_position = (screen_height // 2) - (window_height // 2)

# 设置窗口大小和位置
root.geometry(f"{window_width}x{window_height}+{x_position}+{y_position}")

# 设置窗口不可缩放
root.resizable(width=False, height=False)


# 设置背景颜色
root.configure(bg="#f0f0f0")

# 创建标签
label_menu_name = tk.Label(root, text="菜单名称:", bg="#f0f0f0")
label_menu_name.pack(pady=5)

entry_menu_name = tk.Entry(root, width=50)
entry_menu_name.pack(pady=5)

label_command = tk.Label(root, text="路径:", bg="#f0f0f0")
label_command.pack(pady=5)

entry_command = tk.Entry(root, width=50)
entry_command.pack(pady=5)

# 创建文件选择按钮框架
file_frame = tk.Frame(root, bg="#f0f0f0")
file_frame.pack(pady=5)

# 路径输入框（只读）
entry_command = tk.Entry(file_frame, width=40)
entry_command.pack(side=tk.LEFT, padx=(0, 5))

# 文件选择按钮
browse_button = tk.Button(file_frame, text="浏览...", command=browse_file)
browse_button.pack(side=tk.LEFT)

# 创建按钮框架来更好地管理布局
button_frame = tk.Frame(root, bg="#f0f0f0")
button_frame.pack(pady=10)

# 创建添加按钮
add_button = tk.Button(root, text="添加", bg="#4CAF50", fg="white", command=on_button_click)
add_button.pack(pady=20)

# 创建删除按钮
delete_button = tk.Button(root, text="删除", bg="#f44336", fg="white", command=on_delete_button_click)
delete_button.pack(pady=5)

# 绑定回车键事件
root.bind('<Return>', lambda event: on_button_click())

root.mainloop()
